<template>
  <div class="appointment-container">
    <el-card class="box-card">
      <!-- 页面标题 -->
      <div class="section-title">
        <div class="vertical-bar"></div>
        <h2>签约记录</h2>
      </div>

      <!-- 筛选条件区域 - 第一行 -->
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="签约状态">
          <el-select v-model="filters.contractStatus" placeholder="请选择" size="medium" class="my-select" clearable>
            <el-option label="生效中" :value="5" />
            <el-option label="已过期" :value="6" />
          </el-select>
        </el-form-item>

        <el-form-item label="签约机构">
          <el-select v-model="filters.institutionID" placeholder="请选择" size="medium" class="my-select" clearable>
            <el-option v-for="item in organizations" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="医生团队">
          <el-select v-model="filters.serviceDoctor" placeholder="请选择" size="medium" class="my-select" clearable>
            <el-option v-for="item in teams" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item class="export-button">
          <el-button type="info" size="medium" @click="resetFilters">重置筛选</el-button>
          <el-button type="primary" size="medium" @click="exportEasy" style="margin-left: 8px;">导出</el-button>
        </el-form-item>
      </el-form>

      <!-- 筛选条件区域 - 第二行 -->
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="服务包">
          <el-select v-model="filters.serviceItem" placeholder="请选择" size="medium" class="my-select" clearable>
            <el-option v-for="item in packages" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择日期">
          <el-date-picker
              v-model="filters.date"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="medium"
              clearable
          />
        </el-form-item>

        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入关键字" size="medium" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 筛选状态显示 -->
      <div v-if="hasActiveFilters" class="filter-status">
        <el-tag type="info" size="small">
          <el-icon><Filter /></el-icon>
          已应用筛选条件，共找到 {{ total }} 条记录
        </el-tag>
      </div>

      <!-- 签约记录数据表格 -->
      <div class="table-container">
        <el-table :data="tableData" border style="width: 100%;" height="100%">
        <el-table-column type="selection" width="45" />
        <el-table-column label="编号" prop="id" width="70" align="center" header-align="center"/>
        <el-table-column label="签约人姓名" prop="name" width="120" align="center" header-align="center"/>
        <el-table-column label="身份证号" prop="idCard" width="140" align="center" header-align="center"/>
        <el-table-column label="手机号码" prop="phone" width="110" align="center" header-align="center"/>
        <el-table-column label="签约医生团队" prop="teamName" min-width="100" align="center" header-align="center" />
        <el-table-column label="签约医生" prop="doctor" width="85" align="center" header-align="center"/>
        <el-table-column label="签约服务包" prop="packageName" min-width="95" align="center" header-align="center"/>
        <el-table-column label="签约状态" prop="contractStatus" width="70" align="center" header-align="center">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.contractStatus)" size="small">
              {{ getStatusName(scope.row.contractStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="到期时间" prop="expireDate" width="100" align="center" header-align="center">
          <template #default="scope">
            {{ formatDate(scope.row.expireDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center" header-align="center">
          <template #default="{ row }">
            <el-link type="primary" @click="goDetail(row.id)" :underline="false" size="small">查看详情</el-link>
            <el-link type="primary" @click="goRenew(row.id)" :underline="false" style="margin-left: 8px" size="small">续约</el-link>
          </template>
        </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
            background
            layout="total, sizes, first, prev, pager, next, last, jumper"
            :total="total"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :pager-count="7"
            :small="false"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, computed } from 'vue'
import { Search, Filter } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 路由跳转函数
const goDetail = (id) => {
  router.push({ name: 'wait_signdetail', params: { id: id } })
}

const goRenew = (id) => {
  router.push({ name: 'contract_editing', params: { id: id } })
}

// 筛选条件
const filters = ref({
  contractStatus: null,
  institutionID: null,
  serviceDoctor: null,
  serviceItem: null,
  date: null,
  keyword: ''
})

// 分页数据
const tableData = ref([])
const total = ref(0)
const pageSize = ref(20)
const currentPage = ref(1)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}


// 导出表格
const exportEasy = () => {
  location.href = "http://localhost:8080/contract/exportExcel";
}


// 重置筛选条件
const resetFilters = () => {
  filters.value = {
    contractStatus: null,
    institutionID: null,
    serviceDoctor: null,
    serviceItem: null,
    date: null,
    keyword: ''
  };
  currentPage.value = 1
  loadData();
}

// 状态映射配置
const STATUS_MAP = {
  1: '待审核', 2: '待服务', 3: '已驳回', 4: '待支付',
  5: '生效中', 6: '已过期'
};

const STATUS_TAG_MAP = {
  1: 'primary', 2: 'success', 3: 'danger', 4: 'warning',
  5: 'success', 6: 'info'
};

const getStatusName = (statusId) => {
  return STATUS_MAP[statusId] || '未知状态';
};

const getTagType = (statusId) => {
  return STATUS_TAG_MAP[statusId] || 'info';
};

  // 日期格式化（只显示年月日）
  const formatDate = (isoString) => {
    if (!isoString) return '';
    const date = new Date(isoString);
    const pad = (n) => String(n).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
  };

// 数据加载 - 调用后端综合搜索API
const loadData = () => {
  axios.post(`/contract/getAllContract/${currentPage.value}/${pageSize.value}`, filters.value)
    .then((resp) => {
      const data = resp.data.data || [];
      // 只保留生效中(5)和已过期(6)的记录
      const filteredData = data.filter(item => {
        const status = parseInt(item.contractStatus);
        return [5, 6].includes(status);
      });
      
      tableData.value = filteredData;
      total.value = resp.data.total || 0;
    })
    .catch((error) => {
      console.error('数据加载失败:', error);
      tableData.value = [];
      total.value = 0;
    });
};

// 下拉选项数据
const organizations = ref([]);
const teams = ref([]);
const packages = ref([]);

// 加载下拉选项数据
const loadOptions = () => {
  Promise.all([
    axios.get('/institution/getInstitution'),
    axios.get('/team/getAllTeam'),
    axios.get('/package/getAllPackage')
  ]).then(([orgResponse, teamResponse, packageResponse]) => {
    organizations.value = orgResponse.data || [];
    teams.value = teamResponse.data || [];
    packages.value = packageResponse.data || [];
  }).catch(error => {
    console.error('选项数据加载失败:', error);
  });
};

// 监听筛选条件变化
const keywordTimer = ref(null);

// 通用筛选处理函数
const handleFilterChange = () => {
  currentPage.value = 1;
  loadData();
};

// 关键字搜索防抖处理
watch(() => filters.value.keyword, () => {
  clearTimeout(keywordTimer.value);
  keywordTimer.value = setTimeout(handleFilterChange, 500);
});

// 其他筛选条件立即响应
watch(() => [
  filters.value.contractStatus,
  filters.value.institutionID, 
  filters.value.serviceDoctor,
  filters.value.serviceItem,
  filters.value.date
], handleFilterChange);

// 计算属性：检查是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return filters.value.contractStatus !== null ||
         filters.value.institutionID !== null ||
         filters.value.serviceDoctor !== null ||
         filters.value.serviceItem !== null ||
         (filters.value.date && filters.value.date.length === 2) ||
         (filters.value.keyword && filters.value.keyword.trim() !== '');
});

// 初始化
onMounted(() => {
  loadOptions();
  loadData();
});
</script>

<style scoped>
/* ==================== 容器样式 ==================== */
.appointment-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.box-card {
  padding: 24px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* ==================== 标题样式 ==================== */
.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f2f5;
}

.vertical-bar {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  border-radius: 2px;
  margin-right: 12px;
}

.section-title h2 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* ==================== 筛选表单样式 ==================== */
.filter-form {
  display: flex;
  flex-wrap: wrap;
  column-gap: 16px;
  row-gap: 16px;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background-color: #fafbfc;
  border-radius: 6px;
  border: 1px solid #f0f2f5;
}

.export-button {
  margin-left: auto;
}

.el-form-item {
  margin-bottom: 0 !important;
}

.el-form-item__label {
  color: #606266 !important;
  font-weight: 500 !important;
}

/* ==================== 筛选状态样式 ==================== */
.filter-status {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.filter-status .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* ==================== 表格容器样式 ==================== */
.table-container {
  flex: 1;
  margin-top: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* ==================== 表格样式优化 ==================== */
:deep(.el-table) {
  font-size: 13px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  width: 100% !important;
  table-layout: auto;
}

:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
  line-height: 1.4;
  word-break: break-word;
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  font-size: 13px;
}

:deep(.el-table th) {
  padding: 10px 0;
  background-color: #fafbfc;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
  height: auto;
  font-size: 13px;
}

:deep(.el-table td) {
  padding: 10px 0;
  color: #606266;
  border-bottom: 1px solid #f5f7fa;
  height: auto;
  min-height: 38px;
}

:deep(.el-table tbody tr:hover) {
  background-color: #f8f9fb !important;
}

:deep(.el-table--border) {
  border: none;
}

:deep(.el-table--border td, .el-table--border th) {
  border-right: 1px solid #f0f2f5;
}

:deep(.el-table--border th:last-child, .el-table--border td:last-child) {
  border-right: none;
}

/* ==================== 分页样式 ==================== */
.pagination {
  margin-top: 24px;
  text-align: center;
  flex-shrink: 0;
  padding: 16px 0;
  border-top: 1px solid #f0f2f5;
}

:deep(.el-pagination) {
  justify-content: center;
  align-items: center;
  gap: 8px;
}

:deep(.el-pagination .el-pager li) {
  color: #606266;
  font-weight: 500;
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li:hover) {
  color: #409eff;
  background-color: #f0f9ff;
}

:deep(.el-pagination .el-pager li.is-active) {
  color: #ffffff !important;
  background-color: #409eff !important;
  font-weight: 600;
  border-radius: 4px;
}

:deep(.el-pagination .btn-prev, .el-pagination .btn-next, .el-pagination .btn-first, .el-pagination .btn-last) {
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  padding: 0 8px;
  margin: 0 2px;
}

:deep(.el-pagination .btn-prev:hover, .el-pagination .btn-next:hover, .el-pagination .btn-first:hover, .el-pagination .btn-last:hover) {
  color: #409eff;
  background-color: #f0f9ff;
}

/* ==================== 分页器文本自定义 ==================== */
/* 总数文本 */
:deep(.el-pagination__total) {
  color: #606266;
  font-size: 14px;
}

/* 页面大小选择器 */
:deep(.el-pagination__sizes) {
  margin-left: 16px;
}

:deep(.el-pagination__sizes .el-select__selected-item) {
  color: #606266;
  font-size: 14px;
}

/* 跳转部分 */
:deep(.el-pagination__jump) {
  margin-left: 24px;
}

:deep(.el-pagination__jump .el-pagination__editor) {
  margin: 0 8px;
  width: 50px;
  border-radius: 4px;
}

/* 隐藏原始的英文文本 */
:deep(.el-pagination__jump .el-pagination__goto) {
  display: none;
}

:deep(.el-pagination__jump .el-pagination__classifier) {
  display: none;
}

/* 首页末页按钮文本 */
:deep(.el-pagination .btn-first) {
  font-size: 0;
}

:deep(.el-pagination .btn-first::before) {
  content: "<<";
  font-size: 14px;
}

:deep(.el-pagination .btn-last) {
  font-size: 0;
}

:deep(.el-pagination .btn-last::before) {
  content: ">>";
  font-size: 14px;
}

/* ==================== 自定义下拉框样式 ==================== */
:deep(.my-select) {
  width: 160px;
}

:deep(.my-select .el-select__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-shadow: none;
  transition: all 0.3s ease;
  background-color: #ffffff;
  min-height: 36px;
  padding: 0 12px;
}

:deep(.my-select .el-select__wrapper:hover) {
  border-color: #c0c4cc;
}

:deep(.my-select .el-select__wrapper.is-focused) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.my-select .el-select__placeholder) {
  color: #a8abb2;
  font-size: 14px;
  font-weight: 400;
}

:deep(.my-select .el-select__selected-item) {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

:deep(.my-select .el-select__caret) {
  color: #c0c4cc;
  transition: transform 0.3s ease;
}

:deep(.my-select .el-select__wrapper.is-focused .el-select__caret) {
  color: #409eff;
  transform: rotateZ(180deg);
}

/* ==================== 按钮样式优化 ==================== */
:deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--info) {
  background-color: #f4f4f5;
  border-color: #d3d4d6;
  color: #606266;
}

:deep(.el-button--info:hover) {
  background-color: #e9e9eb;
  border-color: #c8c9cc;
}
</style>
